package com.dlc.shop.live.common.listener;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.dto.wukong.ChanneDeleteDTO;
import com.dlc.shop.bean.enums.LiveRoomStatusType;
import com.dlc.shop.bean.enums.ShopStatus;
import com.dlc.shop.bean.event.ShopChangeStatusEvent;
import com.dlc.shop.common.util.Json;
import com.dlc.shop.common.wukongim.constant.WuKongConstant;
import com.dlc.shop.live.common.model.LiveRoom;
import com.dlc.shop.live.common.service.LiveRoomService;
import com.dlc.shop.live.common.vo.LiveMsgItem;
import com.dlc.shop.wukongim.service.WuKongImService;
import lombok.AllArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 店铺改变状态监听
 *
 * @Author lth
 * @Date 2021/11/22 17:18
 */
@Component("liveShopChangeStatusListener")
@AllArgsConstructor
public class ShopChangeStatusListener {

    private final LiveRoomService liveRoomService;
    private final WuKongImService wuKongImService;

    @EventListener(ShopChangeStatusEvent.class)
    public void liveShopChangeStatusListener(ShopChangeStatusEvent event) {
        Long shopId = event.getShopId();
        ShopStatus shopStatus = event.getShopStatus();
        if (Objects.isNull(shopId) || Objects.isNull(shopStatus)) {
            return;
        }
        if (Objects.equals(shopStatus, ShopStatus.OFFLINE)) {
            List<LiveRoom> needEndList = liveRoomService.list(new LambdaQueryWrapper<LiveRoom>()
                    .eq(LiveRoom::getShopId, shopId)
                    .in(LiveRoom::getLiveStatus, LiveRoomStatusType.NO_START.value(), LiveRoomStatusType.STOP.value(), LiveRoomStatusType.LIVING.value()));
            if (CollUtil.isEmpty(needEndList)) {
                return;
            }
            List<Long> roomIds = needEndList.stream().map(LiveRoom::getRoomId).toList();
            // 更改直播间为结束
            liveRoomService.updateLiveRoomStatus(LiveRoomStatusType.FINISHED.value(), roomIds);
            for (Long roomId : roomIds) {
                String channelId = WuKongConstant.LIVE_CHANNEL_PREFIX + roomId;
                // 发送直播结束消息
                LiveMsgItem statusMsg = new LiveMsgItem(WuKongConstant.LIVE_STATUS, LiveRoomStatusType.FINISHED.value());
                wuKongImService.sendLiveRoomMessage(channelId, Json.toJsonString(statusMsg), null);
                // 删除频道
                wuKongImService.deleteChannel(new ChanneDeleteDTO(channelId, 2));
            }
        }
    }
}
